package com.nowcoder.community.config;

import com.nowcoder.community.quartz.PostScoreRefreshJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

@Configuration
public class QuartzConfig {

    // 对Quartz的Job进行配置
    // 配置信息会被初始化到数据库相应表中

    // FactoryBean的作用是简化Bean的实例化过程
    // 1. 通过FactoryBean封装了Bean的实例化过程
    // 2. 将FactoryBean装配到Spring容器中
    // 3. 将FactoryBean注入给其他的Bean, 该Bean就会得到FactoryBean所管理的对象实例

    // 刷新帖子排行榜的定时任务
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setName("PostScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");
        // 声明该任务是否长期保存
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    // 配置Trigger
    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean triggerFactoryBean = new SimpleTriggerFactoryBean();
        triggerFactoryBean.setJobDetail(postScoreRefreshJobDetail);
        triggerFactoryBean.setName("postScoreRefreshTrigger");
        triggerFactoryBean.setGroup("communityTriggerGroup");
        // 每5分钟执行一次帖子排行刷新
        triggerFactoryBean.setRepeatInterval(1000 * 60 * 5);
        // Trigger底层需要存储Job的一些状态
        // 此处初始化存储所用数据结构 -> 默认JobDataMap
        triggerFactoryBean.setJobDataMap(new JobDataMap());
        return triggerFactoryBean;
    }

}
